<template>
  <div>
    <Treeselect
      :value="value"
      :options="tree"
      :disabled="disabled"
      :multiple="multiple"
      :show-count="true"
      no-results-text="暂无数据"
      :normalizer="normalizer"
      no-options-text="暂无数据"
      :style="{width:width}"
      :default-expand-level="2"
      placeholder="请选择"
      :disable-branch-nodes="true"
      :append-to-body="true"
      @input="select"
      @open="open"
      :zIndex="Zindex"
    />

  </div>
</template>

<script>
import request from '@/utils/request'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  components: { Treeselect },
  props: {
    value: [String, Number, Array],
    businessAttr: {
      type: [String,Number],
      default: null
    },
    url: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    Zindex: {
      type: Number,
      default: 999
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tree: [],
      count:0,
      isActive:true,
      deptId: null,
      copyValue: this.value,
      treeList:[],
      api: 'api/jtgDropDown/',
      normalizer(node) {
        //console.log(this.value)
        if (node.children == null || node.children === 'null') {
          delete node.children
        }

        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      }
    }
  },
  watch: {
    initValue() {
      this.deptId = this.initValue ? this.initValue : null
    },
    value(){
      // console.log('watch--this.value',this.value)
      if(this.value === undefined || this.value === null){
        this.$emit('clearData')
      }
    }
  },
  created() {
    this.remoteMethod('')
  },
  methods: {
    // 请求获取商品数据接口
    ajaxGoods(data) {
      return request({
        url: this.url,
        method: 'GET',
        params: {
          keywords: data,
          businessAttr: this.businessAttr
        }
      })
    },
    // 获取远程数据并赋值
    remoteMethod(data) {
      this.ajaxGoods(data).then(res => {
        if (res.content) {
          this.tree = res.content
          this.tree.push({
            id:'0',
            name:' ',
            children:null
          })
         this.calleArr(this.tree)
        }
      }).catch(e => {
        this.tree = []
        this.totalnum = 0
      })
    },
     calleArr(array){
       new Promise(function(resolve) {
         resolve();
       }).then(() => {
       for (var i=0;i<array.length;i++){
           var data=array[i];
          if(data.children){
            data.name=data.name+"";
            if(data.id==this.value){
              this.count++
              //console.log(data.id)
             // console.log(this.count,"sssbbb")
            }
            this.calleArr(data.children) //自己调用自己
          }else{
           //console.log(data.id)
            data.name=data.name+"";
            if(data.id==this.value){
              this.count++
              //console.log(data.id)
             // console.log(this.count,"123456")
            }
          }
        }
       }).then(() => {
       if(this.count==0){
         //console.log(this.tree)
         this.tree.push({
           id:this.value,
           name:' ',
           children:null
         })
         this.tree=this.unique(this.tree)
       }
       });

    },
     unique(arr){
       for (var i = 0, len = arr.length; i < len; i++) {
         for (var j = i + 1, len = arr.length; j < len; j++) {
           if (arr[i].id === arr[j].id) {
             arr.splice(j, 1);
             j--;        // 每删除一个数j的值就减1
             len--;      // j值减小时len也要相应减1（减少循环次数，节省性能）
             // console.log(j,len)

           }
         }
       }
      return arr;
    },
    treeToList(tree){
      // let result = []
      tree.map(item => {
        if(item.children){
          item.children.map(node => {
            this.treeList.push(node)
          })
          this.treeToList(item.children)
        }
      })
      return this.treeList
    },
    select(node) {
      let data = null
      if (this.multiple) {
        data = this.tree.filter(item => node.find(e => item.id === e))
      } else {
        data = this.tree.find(item => item.id === node)
      }
      const list = this.treeToList(this.tree)
      list.map(item => {
        if(item.id === node){
          this.$emit('changeInfos', item)
        }
      })
      this.$emit('input', node)
      this.$emit('change', data)
      this.$emit('changeInfo', data)
    },
    open() {
      this.remoteMethod('')
    }
  }
}
</script>
<style lang="scss">
.vue-treeselect__multi-value-item-container {
  display: inline-block;
  padding-top: 5px;
  padding-right: 5px;
  vertical-align: top;
  line-height: 16px;
}

/**
.vue-treeselect{
  z-index: 2002 !important;
}
**/

.vue-treeselect__control {
  height: 32px;
  line-height: 16px !important;
}
</style>

